package com.bxx.service.impl;

import com.bxx.dao.UserRoleDao;
import com.bxx.pojo.UserRole;
import com.bxx.service.UserRoleService;
import com.bxx.util.DateParse;
import com.bxx.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserRoleServiceImpl implements UserRoleService {

    @Autowired
    private UserRoleDao userRoleDao;

    @Override
    public R getUserRoleByUserId(String userId) {
        List<UserRole> userRoles = userRoleDao.getUserRoleByUserId(userId);
        if (userRoles != null){
            return R.ok(userRoles);
        }
        return R.error("获取用户角色数据失败！");
    }

    @Override
    public R batchInsertUserRole(String userId, List<String> roleIds) {

        //创建用户角色对象
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setUpdateTime(DateParse.parseTimeStamp(new Date()));

        int t = 0;

        for (int i = 0; i < roleIds.size(); i++) {
            userRole.setRoleId(roleIds.get(i));
            Integer r = userRoleDao.insertUserRole(userRole);
            if (r > 0){
                t ++ ;
            }
        }
        return R.ok("共添加" + roleIds.size() + "个角色，成功添加" + t + "个");
    }

    @Override
    public R batchDeleteUserRole(String userId, List<String> roleIds) {
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);

        int t = 0;
        for (int i = 0; i < roleIds.size(); i++) {
            userRole.setRoleId(roleIds.get(i));

            Integer r = userRoleDao.deleteUserRole(userRole);

            if (r > 0){
                t++;
            }
        }

        return R.ok("共删除" + roleIds.size() + "个角色，成功删除" + t + "个");
    }


}
